<?php

namespace app\modules\Admin\models;

use DateTimeInterface;
use goodsModel;
use goodsskupriceModel;
use Illuminate\Database\Eloquent\Model;

class goodspackageModel extends Model
{
    protected $table = 'goods_package';
    protected $primaryKey = 'id';
    protected $appends = ['card_info_arr', 'package_goods_arr'];

    public $timestamps = false;
    /**
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getCardInfoArrAttribute()
    {
        $card_info_arr = [];
        if(!empty($this->attributes['card_info'])){
            $card_info = json_decode($this->attributes['card_info'], true);
            if ($card_info){
                foreach ($card_info as $card){
                    $card_model = pickgoodscardModel::query()->where('id', $card['id'])->first();
                    $card['id'] = intval($card['id']);
                    $card['number'] = intval($card['number']);
                    $card['name'] = $card_model->name;
                    $card['amount'] = $card_model->amount;
                    $card_info_arr[] = $card;
                }
                unset($card);
                unset($card_model);
            }
            unset($card_info);
        }
        return $card_info_arr;
    }

    public function getPackageGoodsArrAttribute()
    {
        $goods_info_arr = [];
        if(!empty($this->attributes['relation_goods_info'])){
            $goods_info = json_decode($this->attributes['relation_goods_info'], true);
            if ($goods_info){
                $goods_table = (new goodsModel())->getTable();
                $price_table = (new goodsskupriceModel())->getTable();
                foreach ($goods_info as $goods){
                    $goods_model = goodsModel::query()
                        ->leftJoin($price_table, "{$goods_table}.id","=", "{$price_table}.goods_id")
                        ->where("{$goods_table}.id", '=', $goods['id'])
                        ->select(["{$goods_table}.id","{$goods_table}.title","{$goods_table}.image","{$price_table}.stock"])->first();
                    $goods['title'] = $goods_model->title;
                    $goods['image'] = $goods_model->image;
                    $goods['stock'] = $goods_model->stock;
                    $goods['id'] = intval($goods['id']);
                    $goods['number'] = intval($goods['number']);
                    $goods_info_arr[] = $goods;
                }
                unset($goods);
                unset($goods_model);
            }
            unset($goods_info);
        }
        return $goods_info_arr;
    }
}